<?php

namespace app\call\controller;

use app\api\model\Land;
use app\api\model\Massif;
use app\api\model\Order;
use app\BaseController;
use EasyWeChat\Factory;
use think\facade\Db;
use think\facade\Log;

class Pay
{

    protected $noNeedLogin = ["*"];

    protected $app;

    public function __construct()
    {
        $this->app = Factory::payment(config('wechat.wechat_pay'));
    }

    /**
     * 抖音通用支付回调
     * @return
     */
    public function orderCallback()
    {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $order_id = $message['out_trade_no'];
            Log::write("支付回调".json_encode($message));
            // 查询订单是否存在
            $order = Order::where(['out_trade_no' => $order_id, 'status' => 0])->find();
            if (!$order) {
                return true;
            }
            try {
                // 用户是否支付成功
                if ($message['return_code'] == 'SUCCESS') {
                    Db::startTrans();
                    $order->status = 1;
                    $order->pay_time = time();
                    $order->transaction_id = $message['transaction_id'];
                    // 处理订单
                    $order->save();
                    //更新地块状态
                    (new Massif())->where(['id' => $order['massif_id']])->update(['is_lock' => 1]);
                    (new Land())->where(['id' => $order['land_id']])->setDec('residue_nums');
                    Db::commit();
                    return true;
                }else{
                    return $fail('支付失败，请稍后再通知我');
                }
            } catch (\Exception $e) {
                Db::rollback();
                Log::error('微信支付:' . $e->getMessage());
            }
        });

        $response->send();
    }
}